/*
 * Copyright (C) 2010 CODEBISTRO LLC, Sunnyvale, California.
 * All rights reserved. Proprietary and Confidential.
 */

package org.codebistro.util;

import com.google.common.base.Strings;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.IOException;

public class Files {
    public static File tempDir() {
         try {
             File temp= File.createTempFile("test", ".dir");
             if (temp.exists())
                 temp.delete();
             temp.mkdirs();
             return temp;
         } catch(IOException ex) { throw Bark.unchecker(ex); }

     }

    public static void rmDir(File dir) {
        for(File file : dir.listFiles()) {
            if  (file.isDirectory())
                rmDir(file);
            else
                file.delete();
        }
        dir.delete();
    }

    public static String toFilePath(String...comps) {
        StringBuffer result= new StringBuffer();
        for(int i= 0; i < comps.length; i++) {
            if (i > 0)
                result.append(File.separator);
            result.append(comps[i]);
        }
        return result.toString();
    }

    public static File newFile(File parent, String...comps) {
        return new File(parent, toFilePath(comps));
    }

    public static boolean equal(File a, File b) {
        try {
            return a.getCanonicalPath().equals(b.getCanonicalPath());
        } catch (IOException e) {
            throw Bark.unchecker(e);
        }
    }

    public static File getFirstCDDrive() {
        FileSystemView fsv = FileSystemView.getFileSystemView();
        File firstCD= null, firstReadOnly= null;
        for (File root : getFileSystemRoots()) {
            // tried to use fsv.isDrive(root) but it doesn't work on the Mac
            if (!root.canWrite()) {
                if (firstReadOnly==null)
                    firstReadOnly= root;
                String desc = fsv.getSystemTypeDescription(root);
                if (!Strings.isNullOrEmpty(desc) && desc.indexOf("CD") >= 0) {
                    if (firstCD==null)
                        firstCD= root;
                }
            }
            if (firstCD!=null && firstReadOnly!=null)   // no point in iterating any more
                break;
        }
        return firstCD!=null ? firstCD : firstReadOnly;
    }

    public static File[] getFileSystemRoots() {
        File[] result= File.listRoots();
        if (result.length==1 && result[0].getName().length()==0) {
            if (Platform.isMacOS()) {
                result= new File("/Volumes").listFiles();
            } else if (Platform.isUnix()) {
                File volumes= new File("/media");
                if (!volumes.exists())
                    volumes= new File("/mnt");
                result= volumes.listFiles();
            }
        }
        return result;
    }
}
